package com.situ.web.service.impl;

import com.situ.web.dao.IUserDao;
import com.situ.web.dao.impl.UserDaoImpl;
import com.situ.web.pojo.User;
import com.situ.web.pojo.query.UserQuery;
import com.situ.web.service.IUserService;
import com.situ.web.util.JSONResult;
import com.situ.web.util.LayUITableJSONResult;

import java.util.List;

public class UserServiceImpl implements IUserService {
    private IUserDao userDao = new UserDaoImpl();

    //为了封装分页需要的PageInfo，分了好几步完成这个过程
    //中间需要发送两条sql语句
    /*@Override
    public PageInfo selectByPage(Integer pageNo, Integer pageSize) {
        int offset = (pageNo - 1) * pageSize;
        List<User> list = userDao.selectByPage(offset, pageSize);

        int totalCount = userDao.selectTotalCount();
        int totalPage = (int)Math.ceil((double) totalCount / pageSize);

        PageInfo<User> pageInfo = new PageInfo(list, pageNo, pageSize, totalPage);
        return pageInfo;
    }*/

    @Override
    public LayUITableJSONResult selectByPage(UserQuery userQuery) {
        List<User> list = userDao.selectByPage(userQuery);

        int totalCount = userDao.selectTotalCount(userQuery);

        return LayUITableJSONResult.ok(totalCount, list);
    }

    @Override
    public User login(String name, String password) {
        return userDao.login(name, password);
        //return userDao.login(name, MD5Util.MD5Encode(password));
    }

    @Override
    public JSONResult deleleById(int id) {
        int count = userDao.deleteById(id);
        return count == 1 ? JSONResult.ok("删除成功") : JSONResult.error("删除失败");
    }

    @Override
    public JSONResult deleteAll(String[] ids) {
        int count = 0;
        for (String id : ids) {
            count += userDao.deleteById(Integer.parseInt(id));
        }
        return count == ids.length ? JSONResult.ok("删除成功") : JSONResult.error("删除失败");
    }

    @Override
    public JSONResult add(User user) {
        int count = userDao.add(user);
        return count == 1 ? JSONResult.ok("添加成功") : JSONResult.error("添加失败");
    }

    @Override
    public User selectById(int id) {
        return userDao.selectById(id);
    }

    @Override
    public JSONResult update(User user) {
        int count = userDao.update(user);
        return count == 1 ? JSONResult.ok("更新成功") : JSONResult.error("更新失败");
    }

    public static void main(String[] args) {
        int totalCount = 12;
        int pageSize = 5;
        int totalPage = (int)Math.ceil((double) totalCount / pageSize);
        System.out.println(totalPage);// 3
    }
}
